/*
 * @Description: vuex持久化存储
 * @Author: 梁晓雨
 * @Date: 2025-01-23 00:22:59
 */
import { createStore, Store } from 'vuex'
import sercretKey from "../utils/SercretKey";
import createPersistedState from "vuex-persistedstate";
import { set, get } from "idb-keyval";
// 定义User
export interface User {
  userId: number;
  email: string;
  username: string;
  rights: string;
}

// State类型
export interface State {
  user: User | null;
  userfriend: User | null;
}

const store = createStore<State>({
  state: {
    user: null,   // 初始为空
    userfriend: null,  // 当前好友博客信息，初始为空
  },
  mutations: {
    // 更新当前用户信息
    setUser(state, usernew: User) {
      // 对身份信息加密
      state.user = usernew;
    },
    // 更新当前好友博客信息
    setUserFriend(state, userfriendnew: User) {
      state.userfriend = userfriendnew;
    },
    // 清除当前用户信息
    clearUser(state) {
      state.user = null;
    }
  },
  actions: {
    //  提交mutation更新state
    setUser({ commit }, usernew: User) {
      commit('setUser', usernew);
    },
    setUserFriend({ commit }, userfriendnew: User) {
      commit('setUser', userfriendnew);
    },
    logout({ commit }) {
      commit('clearUser');  // 调用mutation 清空user
    }
  },
  getters: {
    // 获取当前用户信息
    getUser(state): User | null {
      const user = state.user;
      // console.log(user);

      // // 对身份信息解密
      // if(user){
      //   user.rights = sercretKey.decryptData(user.rights);
      // }
      // console.log(user);

      return user;
    },
    // 获取当前好友博客信息
    getUserFriend(state): User | null {
      return state.userfriend;
    },
  },
  plugins: [createPersistedState()]
});

export default store;
